# myadmin/views.py 中定义如下视图
import json
import time
import oss2
import uuid
import shutil
# import pandas
import datetime
import requests
from django.shortcuts import render
from django.views import View
from django.db.transaction import atomic
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login
from django.contrib.sessions.models import Session
from django.contrib.auth.hashers import check_password
from django.http import HttpResponse, HttpResponseRedirect

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import reverse,redirect
from libs.utils.ajax import ajax_ok, ajax_fail
from django.contrib.auth.hashers import make_password
from libs.utils.com_func import Struct
from django.contrib.auth import authenticate, login, get_user_model
User = get_user_model()
from django.core.paginator import Paginator
from libs.tl_models.turing.anyang.models import TeachingArrangement, ExpArrangement, PracticeArrangement, \
    Subject, MarkResult, TeacherData, CourseAverageScore
from myadmin.common.common import down_excel
from myadmin.common.common import down_load_image, remove_image, Bytesio_image, \
    upload_oss_file, down_search_video, media_audio, del_file_one, del_file_all, del_search_video, down_ubuntu_video
from datetime import datetime
import xlrd
# 读取表
from xlrd import xldate_as_tuple
import os
import xdrlib

from io import BytesIO
from urllib.request import urlopen
from PIL import Image
from django.http import JsonResponse
# import pandas as pd

def list_dict_duplicate_removal(semester_list, name):
    b = []
    c = []
    for i in semester_list:
        if i[name] in b:
            continue
        b.append(i[name])
        c.append(i)
    return c

# 开始检索
@csrf_exempt
@atomic()
def sumbit_teach_plan(request):
    post = json.loads(request.body, strict=False)
    class_type = int(post.get('class_type'))
    excel_url = post.get('excel_url')
    ben_excel_url = down_excel(excel_url)
    book = xlrd.open_workbook(ben_excel_url)
    if class_type == 0:
        try:
            table = book.sheets()[0]
            # 获取第一个sheet页
            sheet = book.sheets()[0]
            # 读取第一个工作表
            # 获取总行数
            rows = sheet.nrows
            data = []
            # 微信文章属性：wechat_name wechat_id title abstract url time read like number
            now = int(time.time())
            for v in range(1, rows):
                # 每一行数据形成一个列表
                values = table.row_values(v)
                # 列表形成字典
                type = 1  # 理论
                if values[1] == "体育教学部":
                    type = 4
                elif values[1] == "外国语学院":
                    type = 6
                elif values[1] == "艺术设计学院":  # 艺术技法艺术理论都查艺术学院
                    type = 5
                data.append(TeachingArrangement(semester=values[0],
                                        type=type,
                                        department=values[1],
                                        teacher_name=values[2],
                                        position=values[3],
                                        course=values[4],
                                        credit=values[5],
                                        all_period=values[6],
                                        teach_period=values[7],
                                        test_period=values[8],
                                        practice_period=values[9],
                                        other_period=values[10],
                                        class_no=values[11],
                                        class_num=values[12],
                                        evaluation_mode=values[13],
                                        class_sort=values[14],
                                        class_institution=values[15],
                                        week=values[16],
                                        single_double_week=values[17],
                                        section=values[18],
                                        site=values[19],
                                        add_time=now,
                                        update_time=now
                                        ))
            TeachingArrangement.objects.bulk_create(data)
            # 实验
            table1 = book.sheets()[1]
            # 获取第一个sheet页
            sheet1 = book.sheets()[1]
            # 读取第一个工作表
            # 获取总行数
            rows1 = sheet1.nrows
            data1 = []
            # 微信文章属性：wechat_name wechat_id title abstract url time read like number
            now1 = int(time.time())
            for v in range(1, rows1):
                # 每一行数据形成一个列表
                values = table1.row_values(v)
                # # 返回所有数据
                data1.append(ExpArrangement(semester=values[0],
                                           department=values[1],
                                           teacher_name=values[2],
                                           position=values[3],
                                           course=values[4],
                                           period=values[5],
                                           class_no=values[6],
                                           class_num=values[7],
                                           exp_project=values[8],
                                           exp_class=values[9],
                                           exp_num=values[10],
                                           section=values[11],
                                           site=values[12],
                                           add_time=now1,
                                           update_time=now1
                                           ))
            ExpArrangement.objects.bulk_create(data1)
            # 实践
            table2 = book.sheets()[2]
            # 获取第一个sheet页
            sheet2 = book.sheets()[2]
            # 读取第一个工作表
            # 获取总行数
            rows2 = sheet2.nrows
            data2 = []
            # 微信文章属性：wechat_name wechat_id title abstract url time read like number
            now2 = int(time.time())
            for v in range(1, rows2):
                # 每一行数据形成一个列表
                values2 = table2.row_values(v)
                data2.append(PracticeArrangement(semester=values2[0],
                                        department=values2[1],
                                        teacher_name=values2[2],
                                        course=values2[3],
                                        sort=values2[4],
                                        credit=values2[5],
                                        period=values2[6],
                                        week_num=values2[7],
                                        week_time=values2[8],
                                        class_institution=values2[9],
                                        site=values2[10],
                                        add_time=now2,
                                        update_time=now2
                                        ))
            PracticeArrangement.objects.bulk_create(data2)
        except:
            return ajax_fail(message="字段不对应")
    elif class_type == 1:
        try:
            table = book.sheets()[0]
            # 获取第一个sheet页
            sheet = book.sheets()[0]
            # 读取第一个工作表
            # 获取总行数
            rows = sheet.nrows
            data = []
            # 微信文章属性：wechat_name wechat_id title abstract url time read like number
            now = int(time.time())
            for v in range(1, rows):
                # 每一行数据形成一个列表
                values = table.row_values(v)
                # 列表形成字典
                type = 1  # 理论
                if values[1] == "体育教学部":
                    type = 4
                elif values[1] == "外国语学院":
                    type = 6
                elif values[1] == "艺术设计学院":  # 艺术技法艺术理论都查艺术学院
                    type = 5
                data.append(TeachingArrangement(semester=values[0],
                                                type=type,
                                                department=values[1],
                                                teacher_name=values[2],
                                                position=values[3],
                                                course=values[4],
                                                credit=values[5],
                                                all_period=values[6],
                                                teach_period=values[7],
                                                test_period=values[8],
                                                practice_period=values[9],
                                                other_period=values[10],
                                                class_no=values[11],
                                                class_num=values[12],
                                                evaluation_mode=values[13],
                                                class_sort=values[14],
                                                class_institution=values[15],
                                                week=values[16],
                                                single_double_week=values[17],
                                                section=values[18],
                                                site=values[19],
                                                add_time=now,
                                                update_time=now
                                                ))
            TeachingArrangement.objects.bulk_create(data)
        except:
            return ajax_fail(message="字段不对应")
    elif class_type == 2:
        try:
            # 实验
            table1 = book.sheets()[1]
            # 获取第一个sheet页
            sheet1 = book.sheets()[1]
            # 读取第一个工作表
            # 获取总行数
            rows1 = sheet1.nrows
            data1 = []
            # 微信文章属性：wechat_name wechat_id title abstract url time read like number
            now1 = int(time.time())
            for v in range(1, rows1):
                # 每一行数据形成一个列表
                values = table1.row_values(v)
                # # 返回所有数据
                data1.append(ExpArrangement(semester=values[0],
                                            department=values[1],
                                            teacher_name=values[2],
                                            position=values[3],
                                            course=values[4],
                                            period=values[5],
                                            class_no=values[6],
                                            class_num=values[7],
                                            exp_project=values[8],
                                            exp_class=values[9],
                                            exp_num=values[10],
                                            section=values[11],
                                            site=values[12],
                                            add_time=now1,
                                            update_time=now1
                                            ))
            ExpArrangement.objects.bulk_create(data1)
        except:
            return ajax_fail(message="字段不对应")
    elif class_type == 3:
        try:
            # 实践
            table2 = book.sheets()[2]
            # 获取第一个sheet页
            sheet2 = book.sheets()[2]
            # 读取第一个工作表
            # 获取总行数
            rows2 = sheet2.nrows
            data2 = []
            # 微信文章属性：wechat_name wechat_id title abstract url time read like number
            now2 = int(time.time())
            for v in range(1, rows2):
                # 每一行数据形成一个列表
                values2 = table2.row_values(v)
                data2.append(PracticeArrangement(semester=values2[0],
                                                 department=values2[1],
                                                 teacher_name=values2[2],
                                                 course=values2[3],
                                                 sort=values2[4],
                                                 credit=values2[5],
                                                 period=values2[6],
                                                 week_num=values2[7],
                                                 week_time=values2[8],
                                                 class_institution=values2[9],
                                                 site=values2[10],
                                                 add_time=now2,
                                                 update_time=now2
                                                 ))
            PracticeArrangement.objects.bulk_create(data2)
        except:
            return ajax_fail(message="字段不对应")

    return ajax_ok()

@csrf_exempt
@atomic()
def semester_list(request):
    """
        接口功能说明：获取学期列表
        --------------------------------------------
        接口逻辑说明：获取部门列表
        --------------------------------------------
        修改人        修改时间        修改原因
        --------------------------------------------
        张凯          2020-9-22			创建
        --------------------------------------------
        注意事项：
    """
    """
    @api {get} /admin/teachPlan/access/semester/list/?type=1&user_id=1  1 获取学期列表
    @apiGroup teachPlan

    @apiName semester_list
    @apiDescription    获取学期列表
    @apiParam   {Int}     type                          教学类型 1 理论 2 实验 3 实践 4体育 5艺术技法 6外语课 7艺术理论
    @apiParam   {Int}     user_id                       督导老师id

    @apiSuccess {List}     department_list              学期列表
    @apiSuccess {String}   department_list.department       学期名称
    @apiSuccess {String}   department_list.add_time         创建时间
    
    @apiSuccessExample {Array} 返回数据
    返回值类型: JSON
    {
        "message": "",
        "error": "",
        "data": {
            "department_list":[
                {
                    "department":1,
                    "add_time":"12565485685"，
                }    
            ]
        },
        "response": "ok"
    }
    """
    type = int(request.GET.get('type')) # 教学类型 1 理论教学 2 实验教学 3 实践教学
    try:
        if type == 2:
            semester_list = ExpArrangement.objects.filter().values("semester", "add_time")
        elif type == 3:
            semester_list = PracticeArrangement.objects.filter().values("semester", "add_time")
        else:
            if type == 7:
                type = 5
            semester_list = TeachingArrangement.objects.filter(type=type).values("semester", "add_time")
        semester_list = list_dict_duplicate_removal(list(semester_list), "semester")  # 去重
    except:
        return ajax_fail(message="学期信息不存在")
    data = Struct()
    data.semester_list = semester_list
    return ajax_ok(data)

@csrf_exempt
@atomic()
def department_list(request):
    """
        接口功能说明：获取部门列表
        --------------------------------------------
        接口逻辑说明：获取部门列表
        --------------------------------------------
        修改人        修改时间        修改原因
        --------------------------------------------
        张凯           2020-9-22	   创建
        --------------------------------------------
        """
    """
    @api {post} /admin/teachPlan/access/department/list/?user_id=1  2 获取部门列表
    @apiGroup teachPlan
    @apiName department_list
    
    @apiParam     {Int}        type                     排课类型   1理论教学 2实验教学 3实践教学
    @apiParam     {String}     semester                     学期名称
    @apiExample {Array} 获取数据
    获取值类型:JSON
    {
      "type": 1,
      "semester_name": "2021第一学期",
    }

    @apiSuccess {List}     department_list                      教师列表
    @apiSuccess {String}   department_list.department_name          部门姓名
    @apiSuccess {String}   department_list.add_time                 创建时间
    @apiSuccessExample {Array} 返回数据
    返回值类型: JSON
    {
        "message": "",
        "error": "",
        "data": {
            "department_list":[
                {
                    "department_name":"王老师",
                    "add_time":"12565485685"，
                }
            ]
        },
        "response": "ok"
    }
    """
    post = json.loads(request.body, strict=False)
    type = int(post.get('type'))
    semester_name = post.get('semester', '')
    if not semester_name:
        return ajax_fail(message='请先选择学期')
    try:
        if type == 2:
            department_list = ExpArrangement.objects.filter(semester=semester_name).values("department", "add_time")

        elif type == 3:
            department_list = PracticeArrangement.objects.filter(semester=semester_name).values("department",
                                                                                                 "add_time")
        else:
            if type == 7:
                type = 5
            department_list = TeachingArrangement.objects.filter(semester=semester_name, type=type).values("department",
                                                                                                 "add_time")
        department_list = list_dict_duplicate_removal(list(department_list), "department")  # 去重
    except:
        return ajax_fail(message="部门信息不存在")
    data = Struct()
    data.department_list = department_list
    return ajax_ok(data)


@csrf_exempt
@atomic()
def teacher_list(request):
    """
        接口功能说明：获取教师列表
        --------------------------------------------
        接口逻辑说明：获取教师列表
        --------------------------------------------
        修改人        修改时间        修改原因
        --------------------------------------------
        张凯           2020-9-22	   创建
        --------------------------------------------
        """
    """
    @api {post} /admin/teachPlan/access/teacher/list/?user_id=1  3 获取教师列表
    @apiGroup teachPlan
    @apiName teacher_list

    @apiParam     {Int}        type                     排课类型   1理论教学 2实验教学 3实践教学
    @apiParam     {String}     department_name           部门名称
    @apiParam     {String}     semester             学期名称
    @apiExample {Array} 获取数据
    获取值类型:JSON
    {
      "type": 1,
      "department_name": "部门名",
      "semester_name": "2021第一学期"
    }

    @apiSuccess {List}     teacher_list                 教师列表
    @apiSuccess {String}   teacher_list.teacher_name        教师名称
    @apiSuccess {String}   teacher_list.add_time            创建时间
    @apiSuccessExample {Array} 返回数据
    返回值类型: JSON
    {
        "message": "",
        "error": "",
        "data": {
            "teacher_list":[
                {
                    "teacher_name":"教师名称",
                    "add_time":"12565485685"，
                }
            ]
        },
        "response": "ok"
    }
    """
    post = json.loads(request.body, strict=False)
    type = int(post.get('type'))
    semester_name = post.get('semester', '')
    department_name = post.get('department_name', '')
    if not department_name:
        return ajax_fail(message='请先选择部门名称')
    try:
        if type == 2:
            teacher_list = ExpArrangement.objects.filter(department=department_name, semester=semester_name).values(
                "teacher_name", "add_time")
        elif type == 3:
            teacher_list = PracticeArrangement.objects.filter(department=department_name,
                                                              semester=semester_name).values("teacher_name", "add_time")
        else:
            if type == 7:
                type = 5
            teacher_list = TeachingArrangement.objects.filter(department=department_name, type=type,
                                                              semester=semester_name).values("teacher_name", "add_time")
        teacher_list = list_dict_duplicate_removal(list(teacher_list), "teacher_name")  # 去重
    except:
        return ajax_fail(message="教师信息不存在")
    data = Struct()
    data.teacher_list = teacher_list
    return ajax_ok(data)

@csrf_exempt
@atomic()
def course_list(request):
    """
        接口功能说明：获取课程列表
        --------------------------------------------
        接口逻辑说明：获取课程列表
        --------------------------------------------
        修改人        修改时间        修改原因
        --------------------------------------------
        张凯           2020-9-22	   创建
        --------------------------------------------
    """
    """
    @api {post} /admin/teachPlan/access/course/list/?user_id=1  4 获取课程列表
    @apiGroup teachPlan
    @apiName course_list
    
    @apiParam     {Int}        type                     排课类型   1理论教学 2实验教学 3实践教学
    @apiParam     {String}     semester                 学期名称
    @apiParam     {String}     department_name          部门名称
    @apiParam     {String}     teacher_name             教师姓名
    @apiExample {Array} 获取数据
    获取值类型:JSON
    {
      "type": 1,
      "department_name": "教务处",
      "semester_name": "学期名称",
      "teacher_name": "王老师",
    }

    @apiSuccess {List}     course_list                  课程列表
    @apiSuccess {String}   course_list.course_name          课程名称
    @apiSuccess {String}   course_list.add_time             创建时间
    @apiSuccessExample {Array} 返回数据
    返回值类型: JSON
    {
        "message": "",
        "error": "",
        "data": {
            "course_list":[
                {
                    "course_name":"课程名称",
                    "add_time":"12565485685"，
                }
            ]
        },
        "response": "ok"
    }
    """
    post = json.loads(request.body, strict=False)
    type = int(post.get('type'))
    semester_name = post.get('semester', '')
    department_name = post.get('department_name', '')
    teacher_name = post.get('teacher_name', '')

    if not teacher_name:
        return ajax_fail(message='请先选择教师信息')
    try:
        if type == 2:
            course_list = ExpArrangement.objects.filter(department=department_name, semester=semester_name,
                                                          teacher_name=teacher_name).values("course", "add_time")
        elif type == 3:
            course_list = PracticeArrangement.objects.filter(department=department_name, semester=semester_name,
                                                               teacher_name=teacher_name).values("course", "add_time")
        else:
            if type == 7:
                type = 5
            course_list = TeachingArrangement.objects.filter(department=department_name, semester=semester_name, type=type,
                                                               teacher_name=teacher_name).values("course", "add_time")
        course_list = list_dict_duplicate_removal(list(course_list), "course")  # 去重
    except:
        return ajax_fail(message="课程信息不存在")
    data = Struct()
    data.course_list = course_list
    return ajax_ok(data)


@csrf_exempt
@atomic()
def class_no_list(request):
    """
        接口功能说明：获取理论，实验教学安排的上课班号
        --------------------------------------------
        接口逻辑说明：获取理论，实验教学安排的上课班号
        --------------------------------------------
        修改人        修改时间        修改原因
        --------------------------------------------
        张凯           2020-9-22	   创建
        --------------------------------------------
    """
    """
        @api {post} /admin/teachPlan/access/class/no/list/?user_id=1  5 获取理论，实验教学安排的上课班号
        @apiGroup teachPlan
        @apiName class_no_list

        @apiParam     {Int}        type                     排课类型   1理论教学 2实验教学
        @apiParam     {String}     department_name          部门名称
        @apiParam     {String}     course_name              课程名称
        @apiParam     {String}     teacher_name             教师姓名
        @apiParam     {String}     semester                 学期名
        @apiExample {Array} 获取数据
        获取值类型:JSON
        {
          "type": 1,
          "department_name": "教务处",
          "course_name": "课程名称",
          "teacher_name": "王老师",
          "semester": "学期名",
        }

        @apiSuccess {List}     classno_list                上课班号列表
        @apiSuccess {String}   classno_list.class_no         上课班号
        @apiSuccess {String}   classno_list.add_time         创建时间
        @apiSuccessExample {Array} 返回数据
        返回值类型: JSON
        {
            "message": "",
            "error": "",
            "data": {
                "classno_list":[
                    {
                        "class_no":"006",
                        "add_time":"12565485685"，
                    }
                ]
            },
            "response": "ok"
        }
    """
    post = json.loads(request.body, strict=False)
    type = int(post.get('type')) # type 1 理论教学安排 2 实验教学安排
    semester = post.get('semester', '')
    department_name = post.get('department_name', '')
    teacher_name = post.get('teacher_name', '')
    course_name = post.get('course_name', '')
    if not course_name:
        return ajax_fail(message='请先选择课程信息')
    try:
        if type == 2:
             classno_list = ExpArrangement.objects.filter(department=department_name,
                                                         semester=semester, course=course_name,
                                                         teacher_name=teacher_name).values("class_no", "add_time")
        else:
            if type == 7:
                type = 5
            classno_list = TeachingArrangement.objects.filter(department=department_name, type=type,
                                                              semester=semester, course=course_name,
                                                              teacher_name=teacher_name).values("class_no", "add_time")
        classno_list = list_dict_duplicate_removal(list(classno_list), "class_no")  # 去重
    except:
        return ajax_fail(message="上课班号不存在")
    data = Struct()
    data.classno_list = classno_list
    return ajax_ok(data)


@csrf_exempt
@atomic()
def section_list(request):
    """
        接口功能说明：获取理论，实验教学安排的节次信息
        --------------------------------------------
        接口逻辑说明：获取理论，实验教学安排的节次信息
        --------------------------------------------
        修改人        修改时间        修改原因
        --------------------------------------------
        张凯           2020-9-22	   创建
        --------------------------------------------
    """
    """
        @api {post} /admin/teachPlan/access/section/list/?user_id=1  6 获取理论，实验教学安排的节次信息
        @apiGroup teachPlan
        @apiName section_list
        
        @apiParam     {Int}        type                     排课类型   1理论教学 2实验教学
        @apiParam     {String}     department_name          部门名称
        @apiParam     {String}     course_name              课程名称
        @apiParam     {String}     teacher_name             教师姓名
        @apiParam     {String}     semester                 学期名
        @apiParam     {String}     class_no                 上课班号
        @apiExample {Array} 获取数据
        获取值类型:JSON
        {
          "type": 1,
          "department_name": "教务处",
          "course_name": "课程名称",
          "teacher_name": "王老师",
          "semester": "学期名",
          "class_no": "006",
        }

        @apiSuccess {List}     section_list                节次列表
        @apiSuccess {String}   section_list.section          节次名称
        @apiSuccess {String}   section_list.add_time         创建时间
        @apiSuccessExample {Array} 返回数据
        返回值类型: JSON
        {
            "message": "",
            "error": "",
            "data": {
                "section_list":[
                    {
                        "section":"三[5-6节]",
                        "add_time":"12565485685"，
                    }
                ]
            },
            "response": "ok"
        }
    """
    post = json.loads(request.body, strict=False)
    type = int(post.get('type'))
    department_name = post.get('department_name', '')
    course_name = post.get('course_name', '')
    teacher_name = post.get('teacher_name', '')
    semester = post.get('semester', '')
    class_no = post.get('class_no', '')
    if not class_no:
        return ajax_fail(message='请先选择上课班号')
    try:
        if type == 2:
            section_list = ExpArrangement.objects.filter(department=department_name, course=course_name,
                                                         class_no=class_no,
                                                         semester=semester, teacher_name=teacher_name).values(
                "section", "add_time")
        else:
            if type == 7:
                type = 5
            section_list = TeachingArrangement.objects.filter(department=department_name, course=course_name,
                                                              class_no=class_no, type=type,
                                                              semester=semester, teacher_name=teacher_name).values(
                "section", "add_time")
        section_list = list_dict_duplicate_removal(list(section_list), "section")  # 去重
    except:
        return ajax_fail(message="节次信息不存在")
    data = Struct()
    data.section_list = section_list
    return ajax_ok(data)


@csrf_exempt
@atomic()
def site_list(request):
    """
        接口功能说明：获取理论，实验教学安排的地点信息
        --------------------------------------------
        接口逻辑说明：获取理论，实验教学安排的地点信息
        --------------------------------------------
        修改人        修改时间        修改原因
        --------------------------------------------
        张凯           2020-9-22	   创建
        --------------------------------------------
    """
    """
        @api {post} /admin/teachPlan/access/site/list/?user_id=1  7 获取理论，实验教学安排的地点信息
        @apiGroup teachPlan
        @apiName site_list

        @apiParam     {Int}        type                     排课类型   1理论教学 2实验教学
        @apiParam     {String}     department_name          部门名称
        @apiParam     {String}     course_name              课程名称
        @apiParam     {String}     teacher_name             教师姓名
        @apiParam     {String}     semester                 学期名
        @apiParam     {String}     class_no                 上课班号
        @apiParam     {String}     section                  节次信息
        @apiExample {Array} 获取数据
        获取值类型:JSON
        {
          "type": 1,
          "department_name": "教务处",
          "course_name": "课程名称",
          "teacher_name": "王老师",
          "semester": "学期名",
          "class_no": "006",
          "section": "三[5-6节]",
        }

        @apiSuccess {List}     site_list                地点列表
        @apiSuccess {String}   site_list.site             地点
        @apiSuccess {String}   site_list.add_time         创建时间
        @apiSuccessExample {Array} 返回数据
        返回值类型: JSON
        {
            "message": "",
            "error": "",
            "data": {
                "section_list":[
                    {
                        "site":"A-02 202",
                        "add_time":"12565485685"，
                    }
                ]
            },
            "response": "ok"
        }
    """
    post = json.loads(request.body, strict=False)
    type = int(post.get('type'))
    department_name = post.get('department_name', '')
    course_name = post.get('course_name', '')
    teacher_name = post.get('teacher_name', '')
    semester = post.get('semester', '')
    class_no = post.get('class_no', '')
    section = post.get('section', '')
    if not section:
        return ajax_fail(message='请先选择节次地点信息')
    try:
        if type == 2:
            site_list = ExpArrangement.objects.filter(department=department_name, course=course_name,
                                                      teacher_name=teacher_name, class_no=class_no,
                                                      semester=semester, section=section). \
                values("site", "class_num", "add_time")
        else:
            if type == 7:
                type = 5
            site_list = TeachingArrangement.objects.filter(department=department_name, course=course_name,
                                                           teacher_name=teacher_name, class_no=class_no, type=type,
                                                           semester=semester, section=section). \
                values("site", "class_num", "add_time")

        site_list = list_dict_duplicate_removal(list(site_list), "site")  # 去重
    except:
        return ajax_fail(message="地点信息不存在")
    data = Struct()
    data.site_list = site_list

    # teachingArrangement = TeachingArrangement.objects.filter().values("course")
    # teachingArrangement = [dict(t) for t in set([tuple(d.items()) for d in teachingArrangement])]  # 去重
    # data.teachingArrangement = teachingArrangement
    # print(len(data.teachingArrangement),'===')
    return ajax_ok(data)


@csrf_exempt
@atomic()
def week_time_list(request):
    """
        接口功能说明：获取实践周次信息
        --------------------------------------------
        接口逻辑说明：获取实践周次信息
        --------------------------------------------
        修改人        修改时间        修改原因
        --------------------------------------------
        张凯           2020-9-22	   创建
        --------------------------------------------
    """
    """
        @api {post} /admin/teachPlan/access/week/time/list/?user_id=1  8 获取实践周次信息
        @apiGroup teachPlan
        @apiName week_time_list
        @apiParam     {String}     department_name          部门名称
        @apiParam     {String}     course_name              课程名称
        @apiParam     {String}     teacher_name             教师姓名
        @apiParam     {String}     semester                 学期名
        @apiExample {Array} 获取数据
        获取值类型:JSON
        {
          "type": 1,
          "department_name": "教务处",
          "course_name": "课程名称",
          "teacher_name": "王老师",
          "semester": "学期名",
        }

        @apiSuccess {List}     week_times                            周次列表
        @apiSuccess {String}   week_times.week_time                      周次名称
        @apiSuccess {String}   week_times.add_time                       创建时间
        @apiSuccessExample {Array} 返回数据
        返回值类型: JSON
        {
            "message": "",
            "error": "",
            "data": {
                "class_institution":[
                    {
                        "week_time":"10-11",
                        "add_time":"12565485685"，
                    }
                ]
            },
            "response": "ok"
        }
    """
    post = json.loads(request.body, strict=False)
    department_name = post.get('department_name', '')
    semester = post.get('semester', '')
    teacher_name = post.get('teacher_name', '')
    course_name = post.get('course_name', '')
    if not course_name:
        return ajax_fail(message='请先选择课程信息')
    try:
        week_times = PracticeArrangement.objects.filter(department=department_name,
                                                       semester=semester, course=course_name,
                                                       teacher_name=teacher_name).values("week_time", "add_time")
        week_times = list_dict_duplicate_removal(list(week_times), "week_time")  # 去重
    except:
        return ajax_fail(message="周次信息不存在")
    data = Struct()
    data.week_times = week_times
    return ajax_ok(data)


@csrf_exempt
@atomic()
def subject_list(request):
    """
        接口功能说明：获取理论，实验对应的题库信息
        --------------------------------------------
        接口逻辑说明：获取理论，实验对应的题库信息
        --------------------------------------------
        修改人        修改时间        修改原因
        --------------------------------------------
        张凯           2020-9-22	   创建
        --------------------------------------------
    """
    """
        @api {post} /admin/teachPlan/access/subject/list/?user_id=1  9 获取理论，实验对应的题库信息
        @apiGroup teachPlan
        @apiName subject_list
        
        @apiParam     {String}     department_name          部门名称
        @apiParam     {String}     course_name              课程名称
        @apiParam     {String}     teacher_name             教师姓名
        @apiParam     {String}     semester                 学期名
        @apiParam     {String}     class_no                 上课班号
        @apiParam     {String}     section                  节次
        @apiParam     {String}     site                     地点
        @apiParam     {Int}        type                     # 题库类型 1 理论 2 实验 4体育 5艺术技法 6外语课 7艺术理论
        @apiExample {Array} 获取数据
        获取值类型:JSON
        {
          "department_name": "教务处",
          "course_name": "课程名称",
          "teacher_name": "王老师",
          "semester": "学期名",
          "class_no": "",
          "section": "",
          "site": "",
          "type": 1,
        }
        @apiSuccessExample {Array} 返回数据
        返回值类型: JSON
        {
            "message": "",
            "error": "",
            "data": {
                "subject_list":[
                    {
                        "subject_id":12,
                        "quesion":"",
                        "source_value":15,
                        "add_time":"12565485685"，
                    }
                ],
                "department_name":"",
                "course_name":"",
                "teacher_name":"",
                "semester":"",
                "class_no":"",
                "section":"",
                "site":"",
                "type":1,
            },
            "response": "ok"
        }
    """
    post = json.loads(request.body, strict=False)
    department_name = post.get('department_name', '')  # 部门
    course_name = post.get('course_name', '')          # 课程
    teacher_name = post.get('teacher_name', '')        # 教师
    semester = post.get('semester', '')                # 学期
    class_no = post.get('class_no', '')                # 上课班号
    section = post.get('section', '')                  # 节次
    site = post.get('site', '')                        # 地点
    type = int(post.get('type'))                       # 题库类型 1 理论 2 实验 3 实践 4体育 5艺术技法 6外语课 7艺术理论
    data = Struct()
    try:
        subject = Subject.objects.filter(type=type).values("id", "quesion", "source_value", "add_time")
        subject_list = []
        for obj in subject:
            row = Struct()
            row.subject_id = obj.get('id')
            row.quesion = obj.get('quesion')
            row.source_value = obj.get('source_value')
            row.add_time = obj.get('add_time')
            subject_list.append(row)
        data.department_name = department_name
        data.course_name = course_name
        data.teacher_name = teacher_name
        data.semester = semester
        data.class_no = class_no
        data.section = section
        data.site = site
        data.type = type
    except:
        return ajax_fail(message="题库信息不存在")
    data.subject_list = subject_list

    return ajax_ok(data)


@csrf_exempt
@atomic()
def practice_subject_list(request):
    """
            接口功能说明：实践对应的题库信息
            --------------------------------------------
            接口逻辑说明：实践对应的题库信息
            --------------------------------------------
            修改人        修改时间        修改原因
            --------------------------------------------
            张凯           2020-9-22	   创建
            --------------------------------------------
        """
    """
        @api {post} /admin/teachPlan/access/practice/subject/list/?user_id=1  9.1 实践对应的题库信息
        @apiGroup teachPlan
        @apiName practice_subject_list
        
        @apiParam     {String}     department_name          部门名称
        @apiParam     {String}     course_name              课程名称
        @apiParam     {String}     teacher_name             教师姓名
        @apiParam     {String}     semester                 学期名
        @apiParam     {String}     week_time                周次
        @apiExample {Array} 获取数据
        获取值类型:JSON
        {
          "department_name": "教务处",
          "course_name": "课程名称",
          "teacher_name": "王老师",
          "semester": "学期名",
          "class_no": "",
          "week_time": "",
        }
        @apiSuccessExample {Array} 返回数据
        返回值类型: JSON
        {
            "message": "",
            "error": "",
            "data": {
                "subject_list":[
                    {
                        "subject_id":12,
                        "quesion":"",
                        "source_value":15,
                        "add_time":"12565485685"，
                    }
                ],
                "department_name":"",
                "course_name":"",
                "teacher_name":"",
                "semester":"",
                "week_time":"",
                "type":3,
            },
            "response": "ok"
        }
    """
    post = json.loads(request.body, strict=False)
    department_name = post.get('department_name', '')           # 部门
    course_name = post.get('course_name', '')                   # 课程
    teacher_name = post.get('teacher_name', '')                 # 教师
    semester = post.get('semester', '')                         # 学期
    week_time = post.get('week_time', '')                       # 周次

    data = Struct()
    try:
        subject = Subject.objects.filter(type=3).values("id", "quesion", "source_value", "add_time")
        subject_list = []
        for obj in subject:
            row = Struct()
            row.subject_id = obj.get('id')
            row.quesion = obj.get('quesion')
            row.source_value = obj.get('source_value')
            row.add_time = obj.get('add_time')
            subject_list.append(row)
        data.department_name = department_name
        data.course_name = course_name
        data.teacher_name = teacher_name
        data.semester = semester
        data.week_time = week_time
        data.type = 3
    except:
        return ajax_fail(message="题库信息不存在")
    data.subject_list = subject_list

    return ajax_ok(data)

@csrf_exempt
@atomic()
def submit_mark_result(request):
    """
        接口功能说明：提交打分结果
        --------------------------------------------
        接口逻辑说明：提交打分结果
        --------------------------------------------
        修改人        修改时间        修改原因
        --------------------------------------------
        张凯           2020-9-22	   创建
        --------------------------------------------
    """
    """
        @api {post} /admin/teachPlan/submit/mark/result/?user_id=1  9.2 提交打分结果
        @apiGroup teachPlan
        @apiName submit_mark_result
        
        @apiParam     {Int}        week_num                 周数
        @apiParam     {String}     department_name          部门名称
        @apiParam     {String}     course_name              课程名称
        @apiParam     {String}     teacher_name             教师姓名
        @apiParam     {String}     semester                 学期名

        @apiParam     {String}     class_no                 上课班号(理论实验特有)
        @apiParam     {String}     section                  节次(理论实验特有)
        @apiParam     {String}     site                     地点(理论实验特有)

        @apiParam     {String}     week_time                周次(实践特有)

        @apiParam     {Int}        type                     类型 题库类型 1 理论 2 实验 3 实践 4体育 5艺术技法 6外语课 7艺术理论
        @apiParam     {Int}        all_people_num           应到人数
        @apiParam     {Int}        attendance               实到人数
        @apiParam     {String}     evaluate                 评价
        @apiParam     {String}     image_url                图片链接
        @apiParam     {Float}      gross_score              总分数
        @apiParam     {String}     question_result          题目打分详情 [{"question":"题干....", "score":"9.5"}....]
        @apiExample {Array} 获取数据
        获取值类型:JSON
        {
          "week_num": 2,
          "department_name": "教务处",
          "course_name": "课程名称",
          "teacher_name": "王老师",
          "semester": "学期名",
          "class_no": "上课班号(理论实验特有)",
          "section": "节次(理论实验特有)",
          "site": "地点(理论实验特有)",
          "week_time": "周次(实践特有)",
          "type": 1,
          "all_people_num": 10,
          "attendance": 10,
          "evaluate": "评价",
          "remark": "备注",
          "image_url": "",
          "gross_score": 62.5,
          "question_result": [
                {
                    "question":"题干....",
                    "score":9.5
                }
          ]
        }
        @apiSuccessExample {Array} 返回数据
        返回值类型: JSON
        {
            "message": "",
            "error": "",
            "data": {
            },
            "response": "ok"
        }
    """
    user_id = request.GET.get('user_id')
    post = json.loads(request.body, strict=False)
    week_num = post.get('week_num', '0')                     # 周数
    # 理论，实验
    department_name = post.get('department_name', '')       # 部门
    course_name = post.get('course_name', '')               # 课程
    teacher_name = post.get('teacher_name', '')             # 教师
    semester = post.get('semester', '')                     # 学期
    # 理论，实验
    class_no = post.get('class_no', '')                     # 上课班号
    section = post.get('section', '')                       # 节次
    site = post.get('site', '')                             # 地点
    # 实践
    week_time = post.get('week_time', '')                   # 周次

    type = int(post.get('type'))                                 # 类型
    all_people_num = post.get('all_people_num')             # 应到人数
    attendance = post.get('attendance')                     # 实到人数
    evaluate = post.get('evaluate')                         # 评价
    remark = post.get('remark')                             # 备注
    image_url = post.get('image_url')                       # 图片链接
    gross_score = post.get('gross_score')                   # 总分数
    question_result = post.get('question_result')           # 题目打分详情
    now = int(time.time())
    # try:
    if type == 2:
        arrange_Obj = ExpArrangement.objects.filter(department=department_name, course=course_name,
                                                    teacher_name=teacher_name, semester=semester,
                                                    class_no=class_no, section=section, site=site).last()
    elif type == 3:
        arrange_Obj = PracticeArrangement.objects.filter(department=department_name, course=course_name,
                                                         teacher_name=teacher_name, semester=semester,
                                                         week_time=week_time).last()
    else:
        if type == 7:
            type = 5
        arrange_Obj = TeachingArrangement.objects.filter(department=department_name, course=course_name, type=type,
                                                         teacher_name=teacher_name, semester=semester,
                                                         class_no=class_no, section=section, site=site).last()

    if not arrange_Obj:
        return ajax_fail(message=u"课程安排不存在")

    supervisor_obj = User.objects.filter(id=user_id).last()
    supervisor_name = ""
    if supervisor_obj:
        supervisor_name = supervisor_obj.supervisor_name
    MarkResult.objects.create(arrange_id=arrange_Obj.id, department_name=department_name, teacher_name=teacher_name, supervisor_name=supervisor_name, type=type, user_id=user_id, week_num=week_num,
                              all_people_num=all_people_num, attendance=attendance, evaluate=evaluate,
                              remark=remark, image_url=image_url,question_result=question_result,
                              gross_score=gross_score,add_time=now, update_time=now)


    teacher_data = TeacherData.objects.filter(arrange_id=arrange_Obj.id).last()
    if not teacher_data:
        TeacherData.objects.create(teacher_name=arrange_Obj.teacher_name, arrange_id=arrange_Obj.id,
                                   attend_person_num=1, add_time=now, update_time=now)
    else:
        teacher_data.attend_person_num = teacher_data.attend_person_num + 1
        teacher_data.save()
    course_average_score = CourseAverageScore.objects.filter(arrange_id=arrange_Obj.id).last()
    UserObj = User.objects.filter(id=user_id).last()
    rank = 1
    if UserObj:
        rank = UserObj.rank
    if not course_average_score:
        if rank == 1:
            first_super = json.dumps([gross_score])
            two_super = json.dumps([])
        else:
            first_super = json.dumps([])
            two_super = json.dumps([gross_score])
        CourseAverageScore.objects.create(teacher_name=arrange_Obj.teacher_name, arrange_id=arrange_Obj.id,
                                          first_super=first_super, two_super=two_super,
                                          type=type, add_time=now, update_time=now)
    else:
        if rank == 1:
            first_super_list = list(json.loads(course_average_score.first_super))
            first_super_list.append(gross_score)
            course_average_score.first_super = first_super_list
        else:
            two_super_list = list(json.loads(course_average_score.two_super))
            two_super_list.append(gross_score)
            course_average_score.two_super = two_super_list
        course_average_score.save()

    # except:
    #     return ajax_fail(message=u"提交失败")
    return ajax_ok()

@csrf_exempt
@atomic()
def creat_data(request):
    post = json.loads(request.body.decode('utf-8'), strict=False)  # 获取post传参
    type = post.get("type")  # 1 理论 4体育 5艺术技法 6外语课 7艺术理论
    teaching_rrangement_id = post.get("teaching_rrangement_id", 0)  # 理论id 不存在创建 存在更新
    semester = post.get("semester", "")  # 学期
    department = post.get("department", "")  # 部门
    teacher_name = post.get("teacher_name", "")  # 教师姓名
    position = post.get("position", "")  # 职位
    course = post.get("course", "")  # 课程
    credit = post.get("credit", 0)  # 学分
    all_period = post.get("credit", 0)  # 总学时
    teach_period = post.get("teach_period", 0)  # 讲授学时
    test_period = post.get("test_period", 0)  # 实验学时
    practice_period = post.get("test_period", 0)  # 实践学时
    other_period = post.get("other_period", 0)  # 其它学时
    class_no = post.get("class_no", "")  # 上课班号
    class_num = post.get("class_num", 0)  # 上课人数
    evaluation_mode = post.get("class_no", "")  # 考核方式   下拉选择 考察/考试
    class_sort = post.get("class_sort", "")  # 课程类别
    class_institution = post.get("class_institution", "")  # 上课班级机构
    week = post.get("week", "")  # 周次
    single_double_week = post.get("single_double_week", "")  # 单双周  下拉选择 单/双
    section = post.get("section", "")  # 节次
    site = post.get("site", "")  # 地点

    teaching_arrangement = TeachingArrangement.objects.filter(id=teaching_rrangement_id)
    now = int(time.time())
    if teaching_arrangement:  # 更新
        try:
            teaching_arrangement.update(
                **{"semester": semester, "type":type, "department": department, "teacher_name": teacher_name, "position": position,
                   "course": course, "credit": credit, "all_period": all_period, "teach_period": teach_period, "test_period": test_period,
                   "practice_period": practice_period, "other_period": other_period, "class_no": class_no, "class_num": class_num,
                   "evaluation_mode": evaluation_mode, "class_sort": class_sort, "class_institution": class_institution, "week": week,
                   "single_double_week": single_double_week, "section": section, "site": site, "update_time": now})
        except:
            return ajax_fail(message="更新失败，请检查输入数据")
    else:
        try:
            TeachingArrangement.objects.create(semester=semester, type=type, department=department, teacher_name=teacher_name, position=position,
                                                course=course, credit=credit, all_period=all_period, teach_period=teach_period, test_period=test_period,
                                                practice_period=practice_period, other_period=other_period, class_no=class_no, class_num=class_num,
                                                evaluation_mode=evaluation_mode, class_sort=class_sort, class_institution=class_institution, week=week,
                                                single_double_week=single_double_week, section=section, site=site, add_time=now, update_time=now)
        except:
            return ajax_fail(message="创建失败，请检查输入数据")
    return ajax_ok()


@csrf_exempt
@atomic()
def arrangement_list(request):
    post = json.loads(request.body.decode('utf-8'), strict=False)  # 获取post传参
    page = post.get("page", 1)  # 分页页码
    teacher_name = post.get("teacher_name", "")  # 教师姓名
    print(teacher_name,'========')
    if teacher_name:
        arrangement_list = TeachingArrangement.objects.filter(teacher_name__icontains=teacher_name).values("id", "semester", "department",
                           "teacher_name", "position", "course", "credit", "all_period", "teach_period", "test_period", "practice_period",
                           "other_period", "class_no", "class_num", "evaluation_mode", "class_sort", "class_institution", "week",
                            "single_double_week", "section", "site", "add_time").order_by("id")
    else:
        arrangement_list = TeachingArrangement.objects.filter().values("id", "semester", "department",
                           "teacher_name", "position", "course", "credit", "all_period", "teach_period", "test_period", "practice_period",
                           "other_period", "class_no", "class_num", "evaluation_mode", "class_sort", "class_institution", "week",
                            "single_double_week", "section", "site", "add_time").order_by("id")
    data = Struct()
    if arrangement_list:
        paginator = Paginator(arrangement_list, 10)  # 实例化分页对象，每页展示10条记录
        total_page = paginator.num_pages  # 总页数
        try:
            arrangement_list = paginator.page(page).object_list  # 获取某页对应的记录
        except PageNotAnInteger:
            page = 1
            arrangement_list = paginator.page(page).object_list  # 如果页面不是整数，取第一页的记录
        except EmptyPage:
            page = paginator.num_pages
            arrangement_list = paginator.page(paginator.num_pages).object_list  # 如果页码太大，取最后一页记录

        arrangement_data_list = []
        for obj in arrangement_list:
            row = Struct()
            row.id = obj.get("id")  # 用户id
            row.semester = obj.get("semester", "")
            row.department = obj.get("department", "")
            row.teacher_name = obj.get("teacher_name", "")
            row.position = obj.get("position", "")
            row.course = obj.get("course", "")
            row.credit = obj.get("credit", "")
            row.all_period = obj.get("all_period", 0)
            row.teach_period = obj.get("teach_period", 0)
            row.test_period = obj.get("test_period", 0)
            row.practice_period = obj.get("practice_period", 0)
            row.other_period = obj.get("other_period", 0)
            row.class_no = obj.get("class_no", "")
            row.class_num = obj.get("class_num", 0)
            row.evaluation_mode = obj.get("evaluation_mode", "")
            row.class_sort = obj.get("class_sort", "0.0")
            row.class_institution = obj.get("class_institution", "")
            row.week = obj.get("week", "")
            row.single_double_week = obj.get("single_double_week", "")
            row.section = obj.get("section", "")
            row.site = obj.get("site", "")
            row.site = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(obj.get("add_time")))
            arrangement_data_list.append(row)
    else:
        arrangement_data_list = []
        total_page = 0
        page = 0

    data.arrangement_data_list = arrangement_data_list
    data.total_page = total_page  # 总页码
    data.current_page = page  # 页码
    return ajax_ok(data)



@csrf_exempt
@atomic()
def delete_arrangement(request):
    teaching_rrangement_id = request.GET.get("teaching_rrangement_id", 0)  # 类别ID
    admin_user = TeachingArrangement.objects.filter(id=teaching_rrangement_id)
    if admin_user:  # 删除
        admin_user.delete()
    else:
        return ajax_fail(message="删除数据不存在")
    return ajax_ok()
